package com.wry.netty.utils;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * <h1>  <h1>
 *
 * @author wry
 * @since 2023/4/18 15:33
 */
@Data
@AllArgsConstructor
public class ClientAppCreateFactory<T extends ChannelInboundHandlerAdapter> {
    private int port;

    private T handler;

    public void run() {
        final NioEventLoopGroup workLoopGroup   = new NioEventLoopGroup();

        try {
            final Bootstrap clientBootstrap = new Bootstrap();
            clientBootstrap.group(workLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(handler);
                        }
                    })
                    .option(ChannelOption.SO_KEEPALIVE, true);
            final ChannelFuture channelFuture = clientBootstrap.connect("localhost", port).sync();

            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            workLoopGroup.shutdownGracefully();
        }
    }

    public static <T extends ChannelInboundHandlerAdapter> ClientAppCreateFactory<T> App(int port, T handler){
        return new ClientAppCreateFactory<>(port, handler);
    }
}
